package com.lovose.dao;

import java.util.List;

import org.hibernate.Query;

import org.hibernate.Session;

import com.lovose.bean.Company;
import com.lovose.common.SupportDao;

public class CompanyDaoImpl extends SupportDao<Company,Long>implements CompanyDao {
	{
		this.entityClass=Company.class;
	}
	
	@SuppressWarnings("unchecked")
	public List<Company> findAll() {
		Session session=null;
		try{
			session=this.getSession();
			session.beginTransaction();
			Query query =session.createQuery("from "+Company.class.getName()); 
			List<Company> values=query.list();
			session.getTransaction().commit();
			return values;
		}catch(RuntimeException e){
			this.rollback(session);
			throw e;
		}finally{
			this.close(session);
		}
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<Company> findByName(String keyword) {
		Session session = null;

		try {
			session = this.getSession();
			session.beginTransaction();
			Query query = session.createQuery("from " + Company.class.getName()
					+ " p where p.name	 like ? escape '!'");
			query
					.setParameter(0, "%"
							+ keyword.replaceAll("%", "!%").replaceAll("_",
									"!_") + "%");

			// Query query = session.createQuery("from " +
			// Product.class.getName()
			// + " p where p.name like :keyword escape '!'");
			// query
			// .setParameter("keyword", "%"
			// + keyword.replaceAll("%", "!%").replaceAll("_",
			// "!_") + "%");

			List<Company> values = query.list();

			session.getTransaction().commit();
			return values;
		} catch (RuntimeException e) {
			this.rollback(session);
			throw e;
		} finally {
			this.close(session);
		}
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<Company> findAllOrderBySalary(boolean asc) {
		Session session = null;

		try {
			session = this.getSession();
			session.beginTransaction();
			Query query = session.createQuery("from " + Company.class.getName()
					+ " p where p.address.number>1 order by p.address.number "
					+ (asc ? "" : "desc"));
			List<Company> values = query.list();

			session.getTransaction().commit();
			
			return values;
		} catch (RuntimeException e) {
			this.rollback(session);
			throw e;
		} finally {
			this.close(session);
		}
	}
}
